﻿using AutoMapper;
using MediatR;
using RBAC.Domain.SmartHealthcare;
using RBAC.ErrorCode;
using RBAC.Interstructrue.Base;
using SmartHealthcare.Write.Api.Application.Command.Department;

namespace SmartHealthcare.Write.Api.Application.Handler.Department
{
    public class UpdateDepartmentHandler : IRequestHandler<UpdateDepartmentCommand, APIResult<int>>
    {
        private readonly IBaseRepository<DepartmentModel> departRepository;
        private readonly IMapper mapper;
        private readonly ILogger<UpdateDepartmentHandler> logger;

        public UpdateDepartmentHandler(IBaseRepository<DepartmentModel> departRepository, IMapper mapper, ILogger<UpdateDepartmentHandler> logger)
        {
            this.departRepository = departRepository;
            this.mapper = mapper;
            this.logger = logger;
        }
        /// <summary>
        /// 更新科室信息
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public Task<APIResult<int>> Handle(UpdateDepartmentCommand request, CancellationToken cancellationToken)
        {
            APIResult<int> res = new APIResult<int>();
            var model = departRepository.GetModel(request.Id);
            if (model != null)
            {
                //、修改科室信息
                var departModel =mapper.Map(request,model);
                var r = departRepository.Update(departModel);
                if (r > 0)
                {
                    res.Data = r;
                    res.Code = APIEnums.Success;
                    res.Msg = "更新科室成功";
                    logger.LogInformation("更新科室成功");
                    return Task.FromResult(res);
                }
                else
                {
                    res.Data = r;
                    res.Code = APIEnums.Fail;
                    res.Msg = "更新科室失败";
                    logger.LogError("更新科室失败");
                    return Task.FromResult(res);
                }
            }
            else
            {
                res.Data = 0;
                res.Code = APIEnums.Fail;
                res.Msg = "您要更新的科室不存在";
                logger.LogError("更新科室失败");
                return Task.FromResult(res);
            }

        }
    }
}
